package com.fat.spzx.manager.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.fat.spzx.common.constans.RedisConstans;
import com.fat.spzx.common.exception.AddSysRoleException;
import com.fat.spzx.common.exception.AddSysUserException;
import com.fat.spzx.common.exception.LoginException;
import com.fat.spzx.manager.mapper.SysRoleUserMapper;
import com.fat.spzx.manager.mapper.SysUserMapper;
import com.fat.spzx.manager.service.SysUserService;
import com.fat.spzx.model.dto.system.AssginRoleDto;
import com.fat.spzx.model.dto.system.LoginDto;
import com.fat.spzx.model.dto.system.SysUserDto;
import com.fat.spzx.model.entity.system.SysUser;
import com.fat.spzx.model.vo.common.Result;
import com.fat.spzx.model.vo.common.ResultCodeEnum;
import com.fat.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 实现登录的业务方法
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        //获取验证码的key
        String codeKey = loginDto.getCodeKey();
        //用户输入的验证码
        String captcha = loginDto.getCaptcha();
        //从Redis获取验证码
        String code = (String) redisTemplate.opsForValue().get(RedisConstans.USER_LOGIN_VALIDATECODE + codeKey);

        //判断验证码是否正确
        if(StrUtil.isEmpty(code) || !StrUtil.equalsIgnoreCase(captcha,code)) throw new LoginException(ResultCodeEnum.VALIDATECODE_ERROR);

        //删除验证码
        redisTemplate.delete(RedisConstans.USER_LOGIN_VALIDATECODE + codeKey);

        //获取用户信息
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();

        //根据用户名查询数据
        SysUser sysUser = sysUserMapper.selectByUserName(userName);

        //判断用户是否存在
        if(ObjectUtils.isEmpty(sysUser)) throw new LoginException(ResultCodeEnum.LOGIN_ERROR);

        //判断密码是否正确
        if(!sysUser.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) throw new LoginException(ResultCodeEnum.LOGIN_ERROR);

        //登录成功，生成Token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        //存入redis
        redisTemplate.opsForValue().set(RedisConstans.USER_LOGIN+token,JSONObject.toJSONString(sysUser),7, TimeUnit.DAYS);

        //返回loginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    /**
     * 获取用户信息
     */
    @Override
    public SysUser getUserInfo(String token) {
        //根据token从redis获取用户信息
        String userJson = redisTemplate.opsForValue().get(RedisConstans.USER_LOGIN + token);
        //转换为SysUser对象
        SysUser sysUser = JSONObject.parseObject(userJson, SysUser.class);
        //返回
        return sysUser;
    }

    /**
     * 用户退出登录
     */
    @Override
    public Result logout(String token) {
        //删除redis中的token
        redisTemplate.delete(RedisConstans.USER_LOGIN + token);
        //返回
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    /**
     * 用户条件分页查询接口
     */
    @Override
    public PageInfo<SysUser> findByPageUser(Integer current, Integer limit, SysUserDto sysUserDto) {
        //开启分页
        PageHelper.startPage(current,limit);
        //查询数据
        List<SysUser> list = sysUserMapper.findByPageUser(sysUserDto);
        //封装分页对象
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        //返回
        return pageInfo;
    }

    /**
     * 用户添加
     */
    @Override
    public void saveSysUser(SysUser sysUser) {
        //判断用户名是否存在
        SysUser sysUserDB = sysUserMapper.selectByUserName(sysUser.getUserName());
        if (!ObjectUtils.isEmpty(sysUserDB)) throw new AddSysUserException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        //设置数据
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        sysUser.setCreateTime(new DateTime(System.currentTimeMillis()));
        sysUser.setUpdateTime(new DateTime(System.currentTimeMillis()));
        sysUser.setStatus(0);
        sysUser.setIsDeleted(0);
        //保存
        sysUserMapper.saveSysUser(sysUser);
    }

    /**
     * 用户删除
     */
    @Override
    public void deleteById(Integer id) {
        //逻辑删除
        sysUserMapper.deleteById(id);
    }

    /**
     * 用户修改
     */
    @Override
    public void updateUser(SysUser sysUser) {
        sysUserMapper.updateByUser(sysUser);
    }

    /**
     * 用户分配角色
     */
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //1.删除已分配
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());

        //2.重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        for (Long roleId : roleIdList) {
            sysRoleUserMapper.saveSysRoleUser(assginRoleDto.getUserId(),roleId);
        }
    }
}
